__author__  = 'Tom-Wilkin Martinussen <tom@oberon.no>'

from AccessControl import ClassSecurityInfo, AuthEncoding

from zope.interface import implements

from Products.CMFCore import permissions
from AccessControl import getSecurityManager, ClassSecurityInfo
from Products.Archetypes.interfaces.orderedfolder import IOrderedFolder
from Products.ATContentTypes.atct import ATFolder, ATFolderSchema
from Products.ATContentTypes.atct import ATCTContent, ATContentTypeSchema
from config import *
from Products.ATContentTypes.configuration import zconf
from Products.Archetypes.public import registerType
from Products.Archetypes.public import DisplayList
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.public import ImageField
from Products.ATContentTypes.content.document import ATDocument

from Products.validation.config import validation
from Products.validation import V_REQUIRED
from Products.validation.validators.SupplValidators import MaxSizeValidator
from Products.CMFCore.permissions import View

validation.register(MaxSizeValidator('checkNewsImageMaxSize',
                                     maxsize=zconf.ATNewsItem.max_file_size))

from Products.validation.validators.SupplValidators import MaxSizeValidator


try:
	from Products.LinguaPlone.public import *
except ImportError:
	# No multilingual support
	from Products.Archetypes.public import *

schema  = ATFolderSchema.copy() + Schema((

	TextField('body',
            searchable = 1,
            required = False,
            allowable_content_types = ('text/plain',
                                       'text/structured',
                                       'text/html',),
            default_output_type = 'text/x-html-safe',
            widget = RichWidget(label = 'Full description'),
           ),
           
          StringField('style',
		    searchable=0,
		    required=True,
		    default='plone',
            vocabulary=DisplayList((('plone', u'Plone style'),
                                    ('osx', u'OSX-style'),
                                    ('aero', u'Aero'),
                                    ('ubuntu', u'Ubuntu'),)),
            widget=SelectionWidget(label=u'Style',
		                           description="Choose progress bar style",
                				   format='select'),
			),
          
		    StringField('subtext',
		              default_output_type='text/plain',
		              allowable_content_types=('text/structured'),
		              widget=StringWidget(label='Sub text',
		              description="Set the text below the progress bar (e.g complete)",
	              ),
	    	),
	    	
            StringField('table_view',
		    searchable=0,
		    required=True,
		    default='show',
            vocabulary=DisplayList((('show', u'Show'),
                                    ('hide', u'Hide'),)),
            widget=SelectionWidget(label=u'Table view',
		                           description="Show or hide the task summary table",
                				   format='select'),
			),
          
		    ImageField('image',
		        required = False,
		        storage = AnnotationStorage(migrate=True),
		        languageIndependent = True,
		        max_size = zconf.ATNewsItem.max_image_dimension,
		        sizes= {'large'   : (768, 768),
		                'preview' : (400, 400),
		                'mini'    : (200, 200),
		                'thumb'   : (128, 128),
		                'tile'    :  (64, 64),
		                'icon'    :  (32, 32),
		                'listing' :  (16, 16),
		               },
		        validators = (('isNonEmptyFile', V_REQUIRED),
		                             ('checkNewsImageMaxSize', V_REQUIRED)),
		        widget = ImageWidget(
		            description = "Will be shown in the news listing, and in the news item itself. Image will be scaled to a sensible size.",
		            description_msgid = "help_news_image",
		            label= "Image",
		            label_msgid = "label_news_image",
		            i18n_domain = "plone",
		            show_content_type = False)
		        ),
		        
		    StringField('imageCaption',
		        required = False,
		        searchable = True,
		        widget = StringWidget(
		            description = "",
		            description_msgid = "help_image_caption",
		            label = "Image Caption",
		            label_msgid = "label_image_caption",
		            size = 40,
		            i18n_domain = "plone")
		        ),
	        IntegerField('total_hours', 
			        searchable=0, 
		            required=False,
		            default=0,
		            widget=IntegerWidget(label='Abono',
			        description='Horas del abono contratado.'),
		          ),		        
 )
)

schema['relatedItems'].widget.visible = True
schema.moveField('relatedItems', pos='bottom')

class Project(ATFolder, ATDocument):
    """ A new project """
    
    schema = schema
    
    meta_type = archetype_name = portal_type = 'Project'
    content_icon = 'projectprogress_icon.gif'
    _at_rename_after_creation = True
    global_allow = 1
    immediate_view = 'projectprogress_view'
    default_view = 'projectprogress_view'
    
    filter_content_types = 1
    allowed_content_types = ('Task', 'TaskExtra', 'Taskfolder')

    
    actions = ({
        'id': 'view',
        'name': 'View',
        'action': 'string:${object_url}/projectprogress_view',
        'permissions': (permissions.View,)
        },{
        'id': 'edit',
        'name': 'Edit',
        'action': 'string:${object_url}/base_edit',
        'permissions': (permissions.ViewManagementScreens,)
        },{
        'id': 'metadata',
        'name': 'Properties',
        'action': 'string:${object_url}/base_metadata',
        'permissions': (permissions.ViewManagementScreens,)
        },)
        
    security = ClassSecurityInfo()
        
    security.declareProtected(View, 'tag')
    def tag(self, **kwargs):
        """Generate image tag using the api of the ImageField
        """
        if 'title' not in kwargs:
            kwargs['title'] = self.getImageCaption()
        return self.getField('image').tag(self, **kwargs)
        
    def __bobo_traverse__(self, REQUEST, name):
        """Transparent access to image scales
        """
        if name.startswith('image'):
            field = self.getField('image')
            image = None
            if name == 'image':
                image = field.getScale(self)
            else:
                scalename = name[len('image_'):]
                if scalename in field.getAvailableSizes(self):
                    image = field.getScale(self, scale=scalename)
            if image is not None and not isinstance(image, basestring):
                # image might be None or '' for empty images
                return image

        return ATDocument.__bobo_traverse__(self, REQUEST, name)

registerType(Project, PROJECTNAME)
